import type { BreadcrumbProps } from 'antd'

// 递归查找路由
const findRoute = (routes: any[], path: string): any => {
  for (const route of routes) {
    if (route.path === path || route.fullPath === path) {
      return route
    }
    if (route.children) {
      const found = findRoute(route.children, path)
      if (found) {
        return found
      }
    }
  }
  return null
}

export const generateBreadcrumbItems = (
  pathname: string, 
  router: any
): BreadcrumbProps['items'] => {
  const breadcrumbItems: BreadcrumbProps['items'] = [
    {
      title: '首页',
    }
  ]

  // 根据当前路径生成面包屑
  const pathParts = pathname.split('/').filter(part => part)
  let currentPath = ''

  pathParts.forEach((part) => {
    currentPath += `/${part}`
    // 使用递归查找路由
    let route: any = findRoute([router.routeTree], currentPath)
    
    if (route) {
      const meta = route.options?.meta || {}
      breadcrumbItems.push({
        title: meta.label || part,
      })
    } else {
      // 如果没有找到确切匹配的路由，尝试查找部分匹配
      const parentPath = currentPath.substring(0, currentPath.lastIndexOf('/'))
      const parentRoute: any = findRoute([router.routeTree], parentPath)
      if (parentRoute) {
        const childRoute = parentRoute.children?.find((r: any) => 
          r.path === `/${part}` || r.path?.includes(part)
        )
        if (childRoute) {
          const meta = childRoute.options?.meta || {}
          breadcrumbItems.push({
            title: meta.label || part,
          })
        } else {
          breadcrumbItems.push({
            title: part,
          })
        }
      } else {
        breadcrumbItems.push({
          title: part,
        })
      }
    }
  })

  return breadcrumbItems
}